// WebSocket相关功能

// 全局变量
let stompClient = null;
let newOrdersMap = new Map(); // 存储新订单

// WebSocket连接函数
function connectWebSocket() {
    const socket = new SockJS('/ws');
    stompClient = Stomp.over(socket);
    
    stompClient.connect({}, function(frame) {
        console.log('Connected to WebSocket: ' + frame);
        
        // 订阅新订单通知
        stompClient.subscribe('/topic/orders/new', function(message) {
            const notification = JSON.parse(message.body);
            handleNewOrderNotification(notification);
        });
        
        // 可以添加其他订阅，如订单状态变更等
    }, function(error) {
        console.error('WebSocket连接失败:', error);
        setTimeout(connectWebSocket, 5000); // 5秒后重连
    });
}

// 处理新订单通知
function handleNewOrderNotification(notification) {
    console.log('收到新订单通知:', notification);
    
    // 如果配送员状态不是空闲，不显示新订单
    if (currentDeliveryPerson && currentDeliveryPerson.status !== 'IDLE') {
        console.log('配送员当前状态不是空闲，忽略新订单');
        return;
    }
    
    // 存储新订单
    newOrdersMap.set(notification.orderNumber, notification);
    
    // 更新新订单列表UI
    updateNewOrdersUI();
    
    // 显示通知
    showAlert(`收到新订单: ${notification.orderNumber}`, 'info');
    
    // 播放提示音
    playNotificationSound();
}

// 初始化WebSocket相关事件监听
function initWebSocketEvents() {
    // 添加关闭新订单区域按钮事件
    const closeNewOrdersBtn = document.getElementById('closeNewOrdersBtn');
    if (closeNewOrdersBtn) {
        closeNewOrdersBtn.addEventListener('click', function() {
            const newOrdersArea = document.getElementById('newOrdersArea');
            if (newOrdersArea) {
                newOrdersArea.style.display = 'none';
            }
        });
    }
}